package com.cjzuji.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cjzuji.rental.Bean.LingLRequest;
import com.cjzuji.rental.Config.LingLConfig;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.pojo.Orders;
import com.cjzuji.rental.service.GCLingLService;
import com.cjzuji.rental.service.LingLService;
import com.cjzuji.rental.util.Tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class GCLingLServiceImpl implements GCLingLService {

    @Autowired
    LingLConfig lingLConfig;
    @Autowired
    GCLingLSaveServiceImpl orderSaveService;
    @Autowired
    OrderMapper orderMapper;
    private static final Logger logger = LoggerFactory.getLogger(GCLingLServiceImpl.class);
    @Override
    public List<Map<String, Object>> getLingLList(String cookie, String token){
        String url = lingLConfig.getGetListUrl();
        LingLRequest lingLRequest = new LingLRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        lingLRequest.setBusinessType(1);
        lingLRequest.setPageNumber(1);
        lingLRequest.setPageSize(10);
        lingLRequest.setQueryType("queryPageList");
        lingLRequest.setRequestSource("businessNewOfListHeaderStatus");
        int pageNum = 1;  // 从第一页开始
        // 2. 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                lingLRequest.setPageNumber(pageNum);
                String json = objectMapper.writeValueAsString(lingLRequest);
                String resStr = Tool.request(url,cookie, token, json,"");
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                //logger.info("dataMap {}",dataMap);
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("records");
                //logger.info("list {}",list);
                if (list != null && list.size() > 0) {
                    for (Map<String, Object> item : list) {
                        //System.out.println("item~~~~~~~~~~~"+item.toString());
                        String orderId = item.get("orderId").toString();
                        List<Map<String, Object>> ScreenServiceList = null;
                        //碎屏险
                        Double screenRisksAmount = 0.0;
                        int screenRisksType = 0;
                        List<Map<String,Object>> screenService = (List<Map<String, Object>>) item.get("orderGoodsService");
                        if(screenService != null){
                            for (Map<String, Object> ScreenServices : screenService){
                                if (ScreenServices.get("status").toString().equals("09")){
                                    screenRisksAmount = Double.parseDouble(ScreenServices.get("servicePrice").toString());
                                    screenRisksType = 1;

                                }
                            }
                        }
                        //获取合同list
                        Map<String,Object> ordercontract = getContractList(cookie,token,orderId);
                        //账单list
                        Map<String,Object> billMap = getBillList(cookie, token,orderId);
                        orderSaveService.getListSave(orderId, item,screenRisksAmount,screenRisksType,ordercontract,billMap);
                    }
                }
                else {
                    break;
                }
                //休息5秒
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    logger.warn("Sleep interrupted", e);
                    Thread.currentThread().interrupt();
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;
    }

    //获取租用中数据
    public List<Map<String, Object>> upDateBillList(String cookie, String token){
        String url = lingLConfig.getGetListUrl();
        LingLRequest lingLRequest = new LingLRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        lingLRequest.setBusinessType(1);
        lingLRequest.setPageNumber(1);
        lingLRequest.setPageSize(10);
        lingLRequest.setQueryType("queryPageList");
        lingLRequest.setRequestSource("businessNewOfListHeaderStatus");
        lingLRequest.setStatus("06");
        int pageNum = 1;  // 从第一页开始
        // 2. 转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                lingLRequest.setPageNumber(pageNum);
                String json = objectMapper.writeValueAsString(lingLRequest);
                String resStr = Tool.request(url,cookie, token, json,"");
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("records");
                //logger.info("list {}",list);
                if (list != null && list.size() > 0) {
                    for (Map<String, Object> item : list) {
                        //System.out.println("item~~~~~~~~~~~"+item.toString());
                        String orderId = item.get("orderId").toString();
                        //获取合同list
                        Map<String,Object> ordercontract = getContractList(cookie,token,orderId);
                        //账单list
                        Map<String,Object> billMap = getBillList(cookie, token,orderId);
                        List<Map<String, Object>> orderBill = (List<Map<String, Object>>) billMap.get("orderByStagesDtoList");
                        //System.out.println("orderBill~~~~~~~~~~~~~~"+orderBill);
                        orderSaveService.getzySave(orderId,item, ordercontract,orderBill);
                    }
                }
                else {
                    break;
                }
                //休息5秒
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    logger.warn("Sleep interrupted", e);
                    Thread.currentThread().interrupt();
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;
    }

    //获取逾期订单数据
    public List<Map<String, Object>> getOverdue(String cookie, String token){
        String url = lingLConfig.getGetListUrl();
        LingLRequest lingLRequest = new LingLRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        lingLRequest.setBusinessType(1);
        lingLRequest.setPageNumber(1);
        lingLRequest.setPageSize(10);
        lingLRequest.setQueryType("queryPageList");
        lingLRequest.setRequestSource("businessNewOfListHeaderStatus");
        lingLRequest.setStatus("20");
        int pageNum = 1;
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                lingLRequest.setPageNumber(pageNum);
                String json = objectMapper.writeValueAsString(lingLRequest);
                String resStr = Tool.request(url,cookie, token, json,"");
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("records");
                //logger.info("list {}",list);
                if (list != null && list.size() > 0) {
                    for (Map<String, Object> item : list) {
                        //System.out.println("item~~~~~~~~~~~"+item.toString());
                        String orderId = item.get("orderId").toString();
                        // 判断 当前的订单号是否在数据库中存在 如果存在  跳出当前循环
                        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("order_id",orderId);
                        List<Orders> existingOrder = orderMapper.selectList(queryWrapper);
                        // 订单已存在
                        if (!existingOrder.isEmpty() ) {
                            // 订单已存在，更新该订单在Orders表中的状态为4 逾期
                            logger.info("订单已存在~~,更新状态",orderId);
                            UpdateWrapper<Orders> updataWrapper = new UpdateWrapper<>();
                            updataWrapper.eq("order_id",orderId)
                                    .set("status",4)
                                    .set("update_time",new Date());
                            orderMapper.update(updataWrapper);

                        }
                        else{
                            logger.info("Orders表中未找到订单~~~",orderId);
                        }
                    }
                }
                else {
                    break;
                }
                //休息5秒
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    logger.warn("Sleep interrupted", e);
                    Thread.currentThread().interrupt();
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;

    }
    //合同详情
    public Map<String,Object> getContractList(String cookie, String token,String orderId) throws JsonProcessingException {
        String contractUrl = lingLConfig.getGetContractUrl()+orderId;
        String contractStr =  Tool.getRequest(contractUrl,cookie, token);
        ObjectMapper rescontractMapper = new ObjectMapper();
        Map<String,Object> resCon=rescontractMapper.readValue(contractStr,Map.class);
        Map<String,Object> contractList = (Map<String,Object>) resCon.get("data");
        //System.out.println("合同详情~~~~~"+contractList);
        return contractList;
    }
    //账单详情
    public Map<String, Object> getBillList(String cookie, String token,String orderId) throws JsonProcessingException {
        System.out.println("orderId~~~~~~"+orderId);
        //带上参数
        LingLRequest lingLRequest = new LingLRequest();
        lingLRequest.setOrderId(orderId);
        //转为JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String JSON = objectMapper.writeValueAsString(lingLRequest);
        String billUrl = lingLConfig.getGetBillUrl();
        String billStr =  Tool.request(billUrl, cookie,token,JSON,"");
        //System.out.println("账单详情~~~~~"+billStr);
        ObjectMapper resbillMapper = new ObjectMapper();
        Map<String,Object> resBill=resbillMapper.readValue(billStr,Map.class);
        Map<String, Object> billMap = (Map<String, Object>) resBill.get("data");
        return billMap;
    }
}
